<template>
	<div style="display: flex;flex-direction: column;width: 100%;height: 100%;">
		<template>
			<div id="container"></div>
			<el-card v-show="pointEditAble"
					 style="width: 250px; flex-direction: column;display: flex; position: absolute; right: 0px;margin-top: 3%; margin-right: 3%;align-items: center;">
				<span>航迹点编辑</span>
				<el-select size="small" style="margin-top: 2px; width: 230px;" placeholder="选择航迹点" v-model="pointId">
					<el-option v-for="(item,index) in path" :label="index" :key="index" :value="index"></el-option>
				</el-select>

				<div style="width: 230px; margin-top: 2px;display: flex; flex-direction: row;justify-content: space-between;">
					<span style="font-size: 1.2ch;color: gray;">经度:{{pointData.longitude}}</span>
					<span style="font-size: 1.2ch;color: gray;">纬度:{{pointData.latitude}}</span>
				</div>
				<div
						style="width: 230px; display: flex;flex-direction: row; margin-top: 2px;align-items: center;justify-content: space-between;">
					<span>高度:</span>
					<el-input size="small" style="width: 180px;" v-model="pointData.altitude"
							  :placeholder="pointData.altitude"></el-input>
				</div>
				<div
						style="width: 230px; display: flex;flex-direction: row; margin-top: 2px;align-items: center;justify-content: space-between;">
					<span>速度:</span>
					<el-input size="small" style="width: 180px;" v-model="pointData.speed"
							  :placeholder="pointData.speed"></el-input>
				</div>
				<div>

				</div>
				<el-select size="small" style="width: 230px; margin-top: 2px;" v-model="pointData.type"
						   placeholder="航迹点类型">
					<el-option label="过路点" value=1></el-option>
					<el-option label="悬停点" value=2></el-option>
					<el-option label="降落点" value=3></el-option>
				</el-select>
				<div style="display: flex;flex-direction: row;justify-content: space-around;">
					<el-button type="success" size="mini" style=" margin-top: 2px;" @click="editPoint()">确认</el-button>
				</div>

			</el-card>
		</template>
		<div style="margin-left: 2%;height: 13%;width: 96%;display: flex;justify-content: space-between; align-items: center;">
			<div>
				<el-button @click="createAndClearRoute()" size="small" type="primary"
						   :disabled="controlButtonDisable">{{controlButton}}</el-button>
				<el-button @click="detailEdit()" v-show="detailEditButtonDisable" size="small"
						   type="primary">{{detailEditButton}}</el-button>
			</div>
			<div>
				<el-input size="small" style="width: 150px" placeholder="输入航线名称"
						  v-model="routeInfo.routeName"></el-input>
				<el-select size="small" style="width: 150px; margin-left: 20px;" v-model="routeInfo.routeType"
						   placeholder="航线类型">
					<el-option label="多旋翼" value=1></el-option>
					<el-option label="固定翼" value=2></el-option>
				</el-select>
				<el-button @click="uploadRoute()" size="small" style="margin-left: 20px;"
						   type="success">上传航线</el-button>
			</div>
		</div>
	</div>

</template>
<script>
	import AMapLoader from "@amap/amap-jsapi-loader"
	import webSetInfo from "../server/webSetInfo";

	export default {
		data() {
			return {
				Rmap: null,
				userInfo: null,
				forbiddenArea: [],
				routeInstance: null, //绘制的路线对象
				path: [], //路径实例
				pointId: null,
				pointData: {
					latitude: null,
					longitude: null,
					altitude: 100,
					speed: 10,
					type: 1
				},

				controlButton: '开启编辑',
				detailEditButton: '轨迹调整',
				pointEditAble: true,
				controlButtonDisable: false,
				detailEditButtonDisable: false,

				polylineEditor: null,

				routeInfo: {
					routeName: '',
					routeType: null,
				}
			}
		},
		watch: {
			pointId(val, oldval) {
				if (val != null) {
					var data = this.path[val]
					this.pointData = data;
				}
			}
		},
		methods: {
			editPoint() {
				//修改航迹点
				if (this.pointId != null) {
					let data = this.path;
					this.path[this.pointId] = this.pointData
					this.$message({
						type: 'success',
						message: '修改成功'
					})
				}
			},
			detailEdit() {
				let that = this;
				if (this.detailEditButton == '轨迹调整') {
					this.pointEditAble = false;
					this.controlButtonDisable = true
					this.detailEditButton = '关闭调整'
					if (this.polylineEditor == null) {
						AMap.plugin(['AMap.PolylineEditor'], function() {
							that.polylineEditor = new AMap.PolylineEditor(that.map, that.routeInstance)
							that.polylineEditor.open()
						});
					} else {
						this.polylineEditor.open()
					}
				} else {
					this.pointEditAble = true;
					this.controlButtonDisable = false
					this.detailEditButton = '路径点编辑'
					this.polylineEditor.close()
					this.formPath(this.routeInstance.getPath());
					this.pointId = null
					this.$message("所有航迹点属性已刷新，请重新设置")
				}
			},
			createAndClearRoute() {
				let that = this;
				this.controlButtonDisable = true;
				if (this.routeInstance == null) {
					this.controlButton = '清空编辑'
					AMap.plugin(['AMap.MouseTool'], function() { //异步同时加载多个插件
						let mousetool = new AMap.MouseTool(that.map)
						mousetool.polyline({
							showDir: true,
							strokeWeight: 5,
							lineCap: "round"
						})
						mousetool.on('draw', function(e) {
							let path = e.obj.getPath()
							mousetool.close(false)
							that.routeInstance = e.obj;
							that.formPath(that.routeInstance.getPath());
							that.controlButtonDisable = false;
							that.detailEditButtonDisable = true;
							if (!that.checkForbidden(path)) {
								that.$message.error("禁止在禁飞区中绘制航线")
								that.createAndClearRoute()
							}
						})
					});
				} else {
					this.controlButton = '开启编辑'
					this.map.remove(this.routeInstance)
					this.routeInstance = null
					this.path = null
					this.pointId = null
					this.polylineEditor = null
					this.controlButtonDisable = false;
					this.detailEditButtonDisable = false;
				}

			},
			checkForbidden(e) {
				//检查是否在禁飞区
				var i, j, data = this.forbiddenArea;
				for (i = 0; i < data.length; i++) {
					for (j = 0; j < e.length; j++) {
						if (data[i].contains(e[j])) {
							return false;
						}
					}
				}
				return true;
			},
			formPath(e) {
				//格式化路径。转化为可上传的格式
				let i, data = [];
				for (i = 0; i < e.length; i++) {
					let lnglat = e[i]
					let point = {};
					point.longitude = lnglat.getLng();
					point.latitude = lnglat.getLat();
					point.altitude = 100;
					point.speed = 10;
					point.type = 1; //过路点:1,悬停点:2,降落点:3
					data.push(point)
				}
				this.path = data;
			},

			uploadRoute() {
				//上传航线
				var that = this;
				if (this.path == null || this.routeInfo.routeName == '' || this.routeInfo.routeType == null) {
					that.$message.error('请完善航线信息');
					return;
				}
				if (this.path.length == 0) {
					that.$message.error('请编辑航线');
					return;
				}
				this.$axios_token ({
					url: `${webSetInfo.apiUrl}` + `/route/upload`,
					method: "post",
					data: {
						routeName: this.routeInfo.routeName,
						routeType: this.routeInfo.routeType,
						routeData: JSON.stringify(this.path)
					}
				})
						.then(res => {
							let result = res.data
							if (res.code == 200  && result) {
								that.createAndClearRoute()
								that.$message({
									type: 'success',
									message: '添加成功'
								})
							} else {
								that.$message.error("未知错误");
							}
						})
			},

			//初始化地图
			initMap() {
				AMapLoader.load({
					key: '72380e4867d40e523e9e2c5f8863c712', //此处填入我们注册账号后获取的Key
					version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					plugins: [''], //需要使用的的插件列表，如比例尺'AMap.Scale'等
				}).then((AMap) => {
					this.map = new AMap.Map("container", { //设置地图容器id
						layers: [
							new AMap.TileLayer.Satellite(),
							new AMap.TileLayer.RoadNet()
						],
						viewMode: "2D", //是否为3D地图模式
						zoom: 15, //初始化地图级别
					});
					let that = this;
					AMap.plugin(['AMap.Scale'], function() { //异步同时加载多个插件
						let scale = new AMap.Scale();
						that.map.addControl(scale);
					});
					that.getForbidden()
				}).catch(e => {
					console.log(e);
				})
			},
			getForbidden() {
				var that = this
				this.$axios_token ({
					url: `${webSetInfo.apiUrl}` + `/route/getData`,
					method: "post",
					data: {
					}
				})
						.then(response => {
							that.loadArea(response.data)
						})
			},

			loadArea(e) {
				//绘制禁飞区
				console.log("loadArea>>>>>",e.ab.cd);
				for (let i = 0; i < e.length; i++) {
					let data = e[i]
					let path = [];
					for (let j = 0; j < data.length; j++) {
						let area = data[j].elementData;
						for (let k=0; k < area.length; k++) {
							path.push(new AMap.LngLat(area[k].longitude, area[k].latitude))
						}
					}
					let polygon = new AMap.Polygon({
						path: path,
						fillColor: '#fd807e',
						borderWeight: 2,
						strokeColor: 'red',
						bubble: true
					})
					this.forbiddenArea.push(polygon)
					this.map.add(polygon)
				}
			},

		},
		mounted() {
			console.log("route begin.......")
			this.initMap()
			this.userInfo = this.$store.state.userAllInfos;
		}

	}
</script>

<style>
	#container {
		width: 96%;
		margin-left: 2%;
		height: 85%;
		margin-top: 2%;
	}

	.amap-logo {
		display: none;
		opacity: 0 !important;
	}

	.amap-copyright {
		opacity: 0;
	}
</style>
